package com.csun.cmny.provider.netty.server;

import io.netty.bootstrap.AbstractBootstrap;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-04-02 19:06
 * @Description:
 */
@Data
@Slf4j
public abstract class NettyServer {

    private int port;

    private int type;

    private ChannelOption channelOption;

    private ChannelInitializer channelInitializer;

    private ChannelHandler handler;

    private ServerBootstrap serverBootstrap;

    private Bootstrap bootstrap;

//    public NettyServer(int port,
//                       int type,
//                       ChannelOption channelOption,
//                       ChannelInitializer channelInitializer,
//                       ServerBootstrap serverBootstrap) {
//        this.port = port;
//        this.type = type;
//        this.channelOption = channelOption;
//        this.channelInitializer = channelInitializer;
//        this.serverBootstrap = serverBootstrap;
//    }

    public NettyServer(int port,
                       int type,
                       ChannelInitializer channelInitializer,
                       AbstractBootstrap bootstrap,
                       ChannelHandler handler) {
        this.port = port;
        this.type = type;
        this.channelInitializer = channelInitializer;
        if (type == Constant.SOCK_STREAM) {
            this.serverBootstrap = (ServerBootstrap) bootstrap;
        }
        if (type == Constant.SOCK_DGRAM) {
            this.bootstrap = (Bootstrap) bootstrap;
            this.handler = handler;
        }
    }

    public void init() {

        try {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();

            if (type == Constant.SOCK_STREAM) {
                serverBootstrap = serverBootstrap.group(bossGroup, workerGroup);
                serverBootstrap = serverBootstrap.channel(NioServerSocketChannel.class);
                serverBootstrap = serverBootstrap.childHandler(channelInitializer);
                serverBootstrap = serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);
                serverBootstrap = serverBootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            }

            if (type == Constant.SOCK_DGRAM) {
                bootstrap = bootstrap.group(bossGroup);
                bootstrap = bootstrap.channel(NioDatagramChannel.class);
                bootstrap = bootstrap.handler(handler);
                bootstrap = bootstrap.option(ChannelOption.SO_BROADCAST, true);
            }

        } catch (Exception e) {
            log.error("netty server init error: {}", e.getMessage());
        }

    }

}
